﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using ListenMusic.Models;
using System.IO;
using System.Drawing;
using System.Drawing.Text;
using System.Drawing.Imaging;
using ListenMusic.Models.Reposistory.User;
using ListenMusic.User_ServiceReference;
namespace ListenMusic.Controllers
{
    public class AccountController : ApplicationController
    {

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        public ActionResult AdminLogOn()
        {
            return View();
        }
        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(string username, string password, string returnURL)
        {
            LogOnModel model = new LogOnModel();
            model.UserName = username;
            model.Password = password;
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    UserReposistory _user = new UserReposistory();
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);                   
                    Session["user"] = model.UserName;
                    return Json(true);
                }
                else
                {
                    return Json("Tài khoản hoặc mật khẩu không đúng.");
                    //ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
            // If we got this far, something failed, redisplay form
            else
            {
                return View(model);
            }
          
        }
        [HttpPost]
        public ActionResult AdminLogOn(string username, string password, string returnURL)
        {
            LogOnModel model = new LogOnModel();
            model.UserName = username;
            model.Password = password;
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    if (Roles.IsUserInRole(model.UserName, "websiteadmin"))
                    {
                        UserReposistory _user = new UserReposistory();
                        FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                        Session["userAdmin"] = model.UserName;
                        return RedirectToAction("Index", "HomeAdmin");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Tài khoản của bạn không thể truy cập vào trang này.");
                        return RedirectToAction("AdminLogOn");
                    }
                }
                else
                {                    
                    ModelState.AddModelError("", "Tên đăng nhập hoặc mật khẩu không đúng.");
                    return RedirectToAction("AdminLogOn");
                }
            }
            // If we got this far, something failed, redisplay form
            else
            {
                return RedirectToAction("AdminLogOn");
            }

        }
        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session.Remove("user");
            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            create_Capcha();
            ViewBag.capcha = "../../Images/Capcha/" + Session["capcha"] + ".gif";
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            string cap = Session["capcha"].ToString();
            if (model.Capcha == cap)
            {
                if (ModelState.IsValid)
                {
                    // Attempt to register the user
                    MembershipCreateStatus createStatus;
                    UserReposistory _user = new UserReposistory();
                    
                    Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
                    Member member = new Member();
                    member.UserName = model.UserName;
                    member.Birthday = model.Birthday;
                    member.MemberName = model.MemberName;
                    member.Phone = model.Phone;
                    member.Picture = "noimage.gif";
                    if (!Roles.RoleExists("WebsiteUser"))
                    {
                        Roles.CreateRole("WebsiteUser");
                    }

                    Roles.AddUserToRole(model.UserName, "WebsiteUser");


                    if (createStatus == MembershipCreateStatus.Success)
                    {

                        bool rs = _user.register(member);
                        if (rs)
                        {
                            deleteAllCapcha();
                        }
                        FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    }
                }

                // If we got this far, something failed, redisplay form
                return View(model);
            }
            else
            {
                return View(model);
            }
        }
        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(string password,string newpassword,string renewpassword)
        {
            ChangePasswordModel model = new ChangePasswordModel();
            model.OldPassword = password;
            model.NewPassword = newpassword;
            model.ConfirmPassword = renewpassword;
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "Mật Khẩu Không Đúng,Vui Lòng Nhập Lại");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Tên đăng nhập đã tồn tại. Vui lòng chọn tên đăng nhập khác";

                case MembershipCreateStatus.DuplicateEmail:
                    return "Email này đã tồn tại. Vui lòng chọn Email khác";

                case MembershipCreateStatus.InvalidPassword:
                    return "Định dạng mật khẩu không đúng. Vui lòng kiểm tra lại";

                case MembershipCreateStatus.InvalidEmail:
                    return "Địa chỉ email không chính xác. Vui lòng kiểm tra lại";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "Tài khoản đăng nhập không đúng. Vui lòng kiểm tra lại";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
        public void create_Capcha()
        {
            Bitmap objBMP = new Bitmap(60, 20);
            Graphics objGraphics = Graphics.FromImage(objBMP);
            objGraphics.Clear(Color.Bisque);
            objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
            Font objFont = new Font("Tahoma", 12, FontStyle.Bold);
            string randomStr = "";
            int[] myIntArray = new int[5];
            int x;
            Random autoRand = new Random();
            for (x = 0; x < 5; x++)
            {
                myIntArray[x] = Convert.ToInt32(autoRand.Next(0, 9));
                randomStr += (myIntArray[x].ToString());
            }
            Session.Add("capcha", randomStr);
            objGraphics.DrawString(randomStr, objFont, Brushes.White, 3, 3);
            //objBMP.Save(Response.OutputStream, ImageFormat.Gif);
            objBMP.Save(Server.MapPath("~/Images/Capcha/") + randomStr + ".gif", ImageFormat.Gif);
            //Response.ContentType = "image/GIF";
            objFont.Dispose();
            objGraphics.Dispose();
            objBMP.Dispose();
        }
        public void deleteAllCapcha()
        {
            string map = Server.MapPath("~/Images/Capcha/");
            string[] filePaths = Directory.GetFiles(map);

            foreach (string filepath in filePaths)
            {
                System.IO.File.Delete(filepath);
            }
        }
    }
}
